<template>
  <div class="student-scores-container">
    <div class="header">
      <div class="filter-container">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="课程名称">
            <el-input
              v-model="queryParams.courseName"
              placeholder="请输入课程名称"
              clearable
              @keyup.enter.native="searchScores"
            ></el-input>
          </el-form-item>
          <el-form-item label="学期">
            <el-select
              v-model="queryParams.semesterId"
              placeholder="请选择学期"
              clearable
              @change="handleSemesterChange"
            >
              <el-option
                v-for="semester in semesterList"
                :key="semester.id"
                :label="semester.year + '学年第' + semester.term + '学期'"
                :value="semester.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchScores">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="content">
      <el-card class="score-summary">
        <div slot="header" class="clearfix">
          <span>成绩概览</span>
        </div>
        <div class="summary-content">
          <div class="summary-item">
            <div class="label">平均分</div>
            <div class="value">{{ scoreStatistics.averageScore || "--" }}</div>
          </div>
          <div class="summary-item">
            <div class="label">总学分</div>
            <div class="value">{{ scoreStatistics.totalCredits || "--" }}</div>
          </div>
          <div class="summary-item">
            <div class="label">已修课程</div>
            <div class="value">{{ scoreStatistics.courseCount || "--" }}</div>
          </div>
          <div class="summary-item">
            <div class="label">绩点</div>
            <div class="value">{{ scoreStatistics.gpa || "--" }}</div>
          </div>
        </div>
      </el-card>

      <el-table
        :data="tableData"
        border
        style="width: 100%; margin-top: 20px"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="courseName" label="课程名称" align="center" />
        <el-table-column prop="courseNo" label="课程代码" align="center" />
        <el-table-column prop="teacherName" label="授课教师" align="center" />
        <el-table-column prop="credit" label="学分" align="center" width="80" />
        <el-table-column prop="score" label="成绩" align="center" width="100">
          <template slot-scope="scope">
            <span :class="getScoreClass(scope.row.score)">{{
              scope.row.score
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="gradePoint"
          label="绩点"
          align="center"
          width="80"
        />
        <el-table-column prop="semesterName" label="学期" align="center" />
        <el-table-column
          prop="examTime"
          label="考试日期"
          align="center"
          width="120"
        >
          <template slot-scope="scope">
            {{ scope.row.examTime ? formatDate(scope.row.examTime) : "--" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="description"
          label="成绩说明"
          align="center"
          width="120"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ scope.row.description || "--" }}
          </template>
        </el-table-column>
        <el-table-column prop="isValid" label="状态" align="center" width="80">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isValid === 1 ? 'success' : 'danger'">
              {{ scope.row.isValid === 1 ? "有效" : "无效" }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="table-pagination"
        background
        layout="total, prev, pager, next, jumper, sizes"
        :current-page="queryParams.pageNo"
        :page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script>
import { getStudentScores } from "@/api/score";
import { getAllSemester } from "@/api/semester";
import { mapState } from "vuex";
import { getCurrentTerm } from "@/utils/getterm";

export default {
  name: "StudentScores",
  computed: {
    ...mapState("user", ["userInfo"]),
  },
  data() {
    return {
      queryParams: {
        courseName: "",
        semesterId: "",
        pageNo: 1,
        pageSize: 10,
      },
      tableData: [],
      total: 0,
      semesterList: [],
      loading: false,
      scoreStatistics: {
        averageScore: 0,
        totalCredits: 0,
        courseCount: 0,
        gpa: 0,
      },
    };
  },
  methods: {
    // 重置查询条件
    resetQuery() {
      this.queryParams = {
        courseName: "",
        semesterId: "",
        pageNo: 1,
        pageSize: 10,
      };
      this.searchScores();
    },

    // 学期选择改变
    handleSemesterChange() {
      this.searchScores();
    },

    // 查询成绩
    async searchScores() {
      this.loading = true;
      try {
        const params = {
          ...this.queryParams,
          semesterId:
            this.queryParams.semesterId !== ""
              ? Number(this.queryParams.semesterId)
              : null,
        };

        const res = await getStudentScores(params);
        if (res.code === 200) {
          this.tableData = res.data.records || [];
          this.total = res.data.total;
          this.scoreStatistics = res.data.statistics || {
            averageScore: 0,
            totalCredits: 0,
            courseCount: 0,
            gpa: 0,
          };
        } else {
          this.$message.error(res.msg || "获取成绩数据失败");
        }
      } catch (error) {
        console.error("获取成绩数据出错:", error);
        this.$message.error("获取成绩数据出错");
      } finally {
        this.loading = false;
      }
    },

    // 获取学期列表
    async getSemesterList() {
      try {
        const res = await getAllSemester();
        if (res.code === 200) {
          this.semesterList = res.data || [];

          // 获取当前学期并设置为默认选择
          if (this.semesterList.length > 0) {
            const currentSemester = getCurrentTerm(this.semesterList);
            if (currentSemester) {
              this.queryParams.semesterId = currentSemester.id;
            }
          }
          return Promise.resolve();
        }
        return Promise.reject(new Error("获取学期列表失败"));
      } catch (error) {
        console.error("获取学期数据出错:", error);
        return Promise.reject(error);
      }
    },

    // 处理页码变化
    handleCurrentChange(page) {
      this.queryParams.pageNo = page;
      this.searchScores();
    },

    // 处理每页显示条数变化
    handleSizeChange(size) {
      this.queryParams.pageSize = size;
      this.queryParams.pageNo = 1;
      this.searchScores();
    },

    // 获取成绩样式
    getScoreClass(score) {
      if (!score || isNaN(score)) return "";
      const numScore = Number(score);
      if (numScore >= 90) return "score-excellent";
      if (numScore >= 80) return "score-good";
      if (numScore >= 70) return "score-average";
      if (numScore >= 60) return "score-pass";
      return "score-fail";
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return "--";
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) return dateStr;

      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");

      return `${year}-${month}-${day}`;
    },
  },
  mounted() {
    // 获取学期列表，然后获取成绩数据
    this.getSemesterList().then(() => {
      this.searchScores();
    });
  },
};
</script>

<style lang="scss" scoped>
.student-scores-container {
  padding: 20px;

  .header {
    margin-bottom: 20px;

    h2 {
      margin-bottom: 20px;
      font-weight: 500;
      color: #303133;
    }

    .filter-container {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      margin-bottom: 20px;
    }
  }

  .content {
    .score-summary {
      margin-bottom: 20px;

      .summary-content {
        display: flex;
        justify-content: space-around;
        flex-wrap: wrap;

        .summary-item {
          text-align: center;
          padding: 10px 20px;

          .label {
            font-size: 14px;
            color: #606266;
            margin-bottom: 5px;
          }

          .value {
            font-size: 24px;
            font-weight: bold;
            color: #303133;
          }
        }
      }
    }

    .table-pagination {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
}

// 成绩颜色样式
.score-excellent {
  color: #67c23a;
  font-weight: bold;
}
.score-good {
  color: #409eff;
  font-weight: bold;
}
.score-average {
  color: #e6a23c;
}
.score-pass {
  color: #909399;
}
.score-fail {
  color: #f56c6c;
  font-weight: bold;
}
</style>